import classNames from 'classnames';
import React, { useContext } from 'react';
import type { YmColProps } from 'ym-design';
import { YmCol } from 'ym-design';
import FormLayoutContext from './Context/FormLayoutContext';
import ErrorList from './ErrorList';
import type { FormItemInputProps } from './interface/FormItemType';

const FormItemInput: React.FC<FormItemInputProps> = (props) => {
  const {
    wrapperCol,
    extra,
    status,
    help,
    fieldId,
    children,
    errors,
    warnings,
    marginBottom,
    onErrorVisibleChanged,
  } = props;

  const { wrapperCol: contextWrapperCol, prefixCls } =
    useContext(FormLayoutContext);

  const baseClassName = `${prefixCls}-item`;
  const mergedWrapperCol: YmColProps = wrapperCol || contextWrapperCol || {};
  const wrapperColClassName = classNames(
    `${baseClassName}-control`,
    mergedWrapperCol.className,
  );

  const inputDom = (
    <div className={`${baseClassName}-control-input`}>
      <div className={`${baseClassName}-control-input-content`}>{children}</div>
    </div>
  );

  const errorListDom =
    marginBottom !== null || errors.length || warnings.length ? (
      <div style={{ display: 'flex', flexWrap: 'nowrap' }}>
        <ErrorList
          fieldId={fieldId}
          errors={errors}
          warnings={warnings}
          help={help}
          helpStatus={status}
          className={`${baseClassName}-explain-connected`}
          onVisibleChanged={onErrorVisibleChanged}
        />
        {!!marginBottom && <div style={{ width: 0, height: marginBottom }} />}
      </div>
    ) : null;

  const extraProps: { id?: string } = {};

  if (fieldId) {
    extraProps.id = `${fieldId}_extra`;
  }

  const extraDom = extra ? (
    <div {...extraProps} className={`${baseClassName}-extra`}>
      {extra}
    </div>
  ) : null;

  return (
    <YmCol {...mergedWrapperCol} className={wrapperColClassName}>
      {
        <>
          {inputDom}
          {errorListDom}
          {extraDom}
        </>
      }
    </YmCol>
  );
};

export default FormItemInput;
